package student.aistar.dao.impl;

import org.apache.ibatis.session.SqlSession;
import student.aistar.Util.MybatisUtil;
import student.aistar.dao.IUserDao;
import student.aistar.model.entity.User;

public class UserDaoImpl implements IUserDao {
    @Override
    public User getByName(String username) {
        //1. 获取SqlSession
        SqlSession session = MybatisUtil.getSqlSession();

        //自动绑定...
        //1. 怎么知道是哪个mapper文件 - 映射文件
        //2. 怎么知道映射文件的哪条sql语句
        //3. 查询的结果怎么知道绑定User对象
        //消除jdbc手动封装结果集的代码

        //sql - xml文件中
        //namespace值.sql的id值
        User user = session.selectOne("userMapper.get", username);
        return user;
    }

    @Override
    public int delById(Integer id) {
        return 0;
    }

    /**
     *     <insert id="save" parameterType="student.aistar.model.entity.User">
     *         insert into user values(#{id}, #{username}, #{password}, #{email}, #{createDate})
     *     </insert>
     *     #{id} #{username}
     *
     *     #{参数那个对象中的属性值}
     *
     *     ①修改了User - getter方法 - 改错了getUsernames, 但是属性username
     *     ②修改了属性usernames, 但是保留了getter方法 - getUsername
     *     ③属性usernames和getter方法都改错
     *      抛出异常 - There is no getter for.....
     *  User user = new User(null,"yang","555",new Date());
     *  tech.aistar.model.entity.User -> Class.forname() -> User user = (User)c.newInstance();
     *
     *
     *  a. 字符串username取出来
     *  有限字符串的处理 "get" + "Username" = "getUsername"
     *
     *  以下两个当中只要满足一个, 就ok
     *  c. Method m = c.getDeclaredMethod("getUsername");
     *  d. 判断m是否存在 - 如果存在 String username = m.invoke(user);
     *  如果不存在, 走e
     *
     *  e. 如果m不存在 - getter错误, 但是属性username
     *      Field f = c.getDeclaredField("username")
     *      判断f是否存在 - String username = f.get(user)
     *
     * @param user
     * @return
     */
    @Override
    public int save(User user) {
        int affectedRows = 0;
        SqlSession session = null;
        try {
            session = MybatisUtil.getSqlSession();
            affectedRows = session.insert("userMapper.save", user);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert session != null;
            session.close();
        }
        return affectedRows;
    }

    @Override
    public int updateUser(User user) {
        return 0;
    }
}
